package com.mg.dubbo.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.mg.dubbo.register.service.MgService;
import com.mg.dubbo.register.service.PoiService;

@Controller
@RequestMapping(value="/")
public class AController {
	@Autowired
	private MgService mgService;
	@Autowired
	private PoiService poiService;
	
	@RequestMapping(value="/index")
	public void index(HttpServletRequest req,HttpServletResponse res) throws IOException{
		String resString = mgService.helloDubbo("xiaogang");
		res.getWriter().print(resString);
	}
	
	@RequestMapping(value="/cry")
	public void cry(HttpServletRequest req,HttpServletResponse res) throws IOException{
		String resString = mgService.cry("xiaoqiang");
		System.out.println(resString);
		res.getWriter().print(resString);
	}
	@RequestMapping(value="/xls")
	public void loadXls(HttpServletRequest req,HttpServletResponse res) throws IOException{
		String sql = "select code '编码',name '名称',parent_code '父级编码' from pub_region";
		JSONObject json = new JSONObject();
		json.put("url", "jdbc:mysql://192.168.56.1:3306/from?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull");
		json.put("username", "root");
		json.put("password", "root");
		json.put("driverClass", "com.mysql.jdbc.Driver");
		String filepath = "E:/2.xls";
		json.put("filepath", filepath);
		poiService.loadTableForXls(sql, json);
		File file = new File(filepath);
		String filename = file.getName();
		 // 以流的形式下载文件。  
        InputStream fis = new BufferedInputStream(new FileInputStream(filepath));  
        byte[] buffer = new byte[fis.available()];  
        fis.read(buffer);  
        fis.close();  
        // 清空response  
        res.reset();
		res.addHeader("Content-Disposition", "attachment;filename="  
                + filename);  
        res.addHeader("Content-Length", "" + file.length());  
        OutputStream toClient = new BufferedOutputStream(  
                res.getOutputStream());  
        res.setContentType("application/vnd.ms-excel;charset=gb2312"); 
        toClient.write(buffer);
	}
}
